package cn.restcloud.example.controller;

import java.io.InputStream;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import cn.restcloud.example.model.UserModel;
import cn.restcloud.framework.core.annotation.bean.BeanConfig;
import cn.restcloud.framework.core.annotation.bean.BeanType;
import cn.restcloud.framework.core.annotation.rest.MethodType;
import cn.restcloud.framework.core.annotation.rest.RestConfig;
import cn.restcloud.framework.view.base.DocAndView;
import cn.restcloud.framework.view.util.ViewUtil;

@BeanConfig(appId = "example",beanId = "MyBatisDemo",beanName = "MyBatis整合示例",beanType = BeanType.CONTROLLER,autowired = false,singleton = true,hotMode = true)
@RestConfig(url = "/rest/example/mybatis")
public class MyBatisDemo {
	@RestConfig(configName = "列出数据记录",method = MethodType.GET,url = "/list")
	public DocAndView listAll()throws Exception{
		 UserModel user;
		 
		//创建一个数据源
	    InputStream is = MyBatisDemo.class.getResourceAsStream("/MyBatis.xml");
	    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		DataSource ds=sqlSessionFactory.getConfiguration().getEnvironment().getDataSource();
		
		//获得mybatis的session对像
		 SqlSession session =sqlSessionFactory.openSession();
		//映射sql的标识字符串
	     String statement = "cn.restcloud.userMapper.getUser";
	     //执行查询返回一个唯一user对象的sql
	     try{
	    	 user = session.selectOne(statement, "11");
	     }finally {
	    	 session.close();
	     }
	     
		DocAndView dv=ViewUtil.getJsonView(user);
		return dv;
	}
	
}
